package cn.iocoder.yudao.framework.business.basic.dao.repository;

import jakarta.annotation.Nullable;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.time.Duration;

/**
 * <pre>
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * 对象类型的 Redis DAO
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * </pre>
 *
 * @author 山野羡民（1032694760@qq.com）
 * @since 2024/12/15
 */
@SuppressWarnings("unused")
@Slf4j
@Repository
public class ObjectRedisRepository {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public boolean hasKey(String key) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }

    public Long increment(String key, long delta) {
        log.trace("REDIS increment：key={},delta={}", key, delta);
        return redisTemplate.opsForValue().increment(key, delta);
    }

    public Long decrement(String key, long delta) {
        log.trace("REDIS decrement：key={},delta={}", key, delta);
        return redisTemplate.opsForValue().decrement(key, delta);
    }

    @Nullable
    public <T> T get(String key) {
        log.trace("REDIS get：key={}", key);
        //noinspection unchecked
        return (T) redisTemplate.opsForValue().get(key);
    }

    public void set(String key, Object value) {
        log.trace("REDIS set：key={},value={}", key, value);
        redisTemplate.opsForValue().set(key, value);
    }

    public void set(String key, Object value, long expiresSeconds) {
        log.trace("REDIS set：key={},value={},expiresSeconds={}", key, value, expiresSeconds);
        redisTemplate.opsForValue().set(key, value, Duration.ofSeconds(expiresSeconds));
    }

    public void setIfAbsent(String key, Object value) {
        log.trace("REDIS setIfAbsent：key={},value={}", key, value);
        redisTemplate.opsForValue().setIfAbsent(key, value);
    }

    public void setIfAbsent(String key, Object value, long expiresSeconds) {
        log.trace("REDIS setIfAbsent：key={},value={},expiresSeconds={}", key, value, expiresSeconds);
        redisTemplate.opsForValue().setIfAbsent(key, value, Duration.ofSeconds(expiresSeconds));
    }


    public void expire(String key, long expiresSeconds) {
        log.trace("REDIS expire：key={},expiresSeconds={}", key, expiresSeconds);
        redisTemplate.expire(key, Duration.ofSeconds(expiresSeconds));
    }

    public void delete(String key) {
        log.trace("REDIS delete：key={}", key);
        redisTemplate.delete(key);
    }

}
